<template>
	<view class="product-detail">
		<!-- 商品图片轮播 -->
		<view class="product-images">
			<swiper class="swiper" indicator-dots="true" indicator-color="rgba(255,255,255,0.6)" indicator-active-color="#ff4444">
				<swiper-item v-for="(image, index) in (product.images || [])" :key="index">
					<image :src="image || '/static/logo.png'" mode="aspectFill" class="product-image"></image>
					<view class="video-play" v-if="index === 0">
						<u-icon name="play-right-fill" size="24" color="#fff"></u-icon>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 价格和基本信息 -->
		<view class="price-section">
			<view class="price-row">
				<text class="price">¥{{ product.price }}</text>
				<text class="sold">已售{{ product.sold }}</text>
			</view>
			<view class="member-price">
				<text>开通店铺会员,享会员专属特权价¥{{ product.memberPrice }}</text>
			</view>
			<view class="coupon-section">
				<view class="coupon-tag">
					<text>满100减10</text>
				</view>
				<view class="get-coupon">
					<text>领券</text>
					<u-icon name="arrow-right" size="12" color="#fff"></u-icon>
				</view>
			</view>
		</view>

		<!-- 商品标题和描述 -->
		<view class="product-info">
			<view class="product-title">{{ product.title }}</view>
			<view class="product-desc">{{ product.description }}</view>
			<view class="action-buttons">
				<view class="share-btn">
					<u-icon name="share" size="16" color="#666"></u-icon>
					<text>分享</text>
				</view>
				<view class="collect-btn" :class="{ 'collected': product.isCollected }" @click="toggleCollect">
					<u-icon name="star-fill" size="16" :color="product.isCollected ? '#ff4444' : '#666'"></u-icon>
					<text>{{ product.isCollected ? '已收藏' : '收藏' }}</text>
				</view>
			</view>
		</view>

		<!-- 规格选择 -->
		<view class="specification-section" v-if="product.specTypes.length > 0">
			<view class="spec-item" @click="showSpecModal">
				<view class="spec-label">
					<text>选择</text>
					<text class="selected-info">已选: {{ getSelectedSpecText() }} {{ selectedSpec.quantity }}件</text>
					<text class="stock-info" v-if="getCurrentStock() > 0">库存: {{ getCurrentStock() }}</text>
					<text class="stock-info out-of-stock" v-else-if="selectedSpec.skuId">库存不足</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
			<view class="spec-item">
				<view class="spec-label">
					<text>参数</text>
					<text class="spec-desc">七天无理由退货 温馨提示</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
			<view class="spec-item">
				<view class="spec-label">
					<text>配送</text>
					<text class="spec-desc">快递配送</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
			<view class="spec-item">
				<view class="spec-label">
					<text>快递</text>
					<text class="spec-desc">¥{{ product.shipping }}</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
			<view class="delivery-address">
				<text>配送至: {{ deliveryAddress }}</text>
			</view>
		</view>

		<!-- 商品评价 -->
			<view class="reviews-section" @click="goToReviews">
				<view class="reviews-header">
					<text class="reviews-title">商品评价({{ reviewStats.total }})</text>
				<view class="reviews-more">
					<text>全部评价</text>
					<u-icon name="arrow-right" size="12" color="#999"></u-icon>
				</view>
			</view>
				<view class="reviews-filters">
					<text class="filter-item active" @click.stop="goToReviewsWithTab('all')">全部({{ reviewStats.total }})</text>
					<text class="filter-item" @click.stop="goToReviewsWithTab('positive')">好评({{ goodReviews }})</text>
					<text class="filter-item" @click.stop="goToReviewsWithTab('neutral')">中评({{ neutralReviews }})</text>
					<text class="filter-item" @click.stop="goToReviewsWithTab('negative')">差评({{ badReviews }})</text>
					<text class="filter-item" @click.stop="goToReviewsWithTab('withImage')">有图({{ imageReviews }})</text>
				</view>
				<view class="reviews-list">
					<view class="review-item" v-for="(review, index) in reviews" :key="index" @click.stop="goToReviewsReview(review)">
					<view class="review-user">
						<image class="user-avatar" :src="review.avatar || defaultAvatar"></image>
						<view class="user-info">
							<text class="username">{{ review.username }}</text>
            <view class="rating">
              <u-icon v-for="i in 5" :key="i" name="star-fill" size="12" :color="i <= (review.rating || 0) ? '#ff4444' : '#ddd'"></u-icon>
            </view>
						</view>
					</view>
					<view class="review-content">
						<text class="review-text">{{ review.content }}</text>
						<text class="review-spec" v-if="review.spec">{{ review.spec }}</text>
					</view>
    <view class="review-images" v-if="review.images && review.images.length">
      <view
        class="review-image-item"
        v-for="(img, idx) in review.images"
        :key="idx"
        @click.stop="previewImage(review.images, idx)"
      >
        <image :src="img" mode="aspectFill" />
      </view>
    </view>
				</view>
			</view>
		</view>

		<!-- 店铺信息 -->
		<view class="store-section">
			<view class="store-info">
				<image class="store-logo" :src="store.logo"></image>
				<view class="store-details">
					<view class="store-name">
						<text>{{ store.name }}</text>
						<text class="self-operated">自营</text>
					</view>
					<view class="store-rating">
						<text class="rating-score">{{ store.rating }}</text>
						<view class="rating-stars">
							<u-icon name="star-fill" size="12" color="#ff4444" v-for="i in 5" :key="i"></u-icon>
						</view>
						<text class="followers">粉丝{{ store.followers }}人</text>
					</view>
				</view>
			</view>
			<view class="visit-store">进店逛逛</view>
		</view>

		<!-- 推荐商品 -->
		<view class="recommended-section" v-if="recommendedProducts.length > 0">
			<view class="section-title">店铺推荐</view>
			<view class="recommended-grid">
				<view class="recommended-item" v-for="(item, index) in safeRecommendedProducts" :key="index" @tap="handleProductClick(item)" @click="handleProductClick(item)">
					<image class="item-image" :src="getSafeImage(item)" mode="aspectFill"></image>
					<view class="item-info">
						<text class="item-title">{{ getSafeTitle(item) }}</text>
						<text class="item-price">¥{{ getSafePrice(item) }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 商品详情 -->
		<view class="product-details">
			<view class="section-title">商品详情</view>
			<view class="detail-content">
				<!-- 商品详情文字内容 -->
				<view v-if="goodsMessage && goodsMessage.goodsContent" class="detail-text">
					<text>{{ goodsMessage.goodsContent }}</text>
				</view>
				<text v-else-if="product.detailDescription && product.detailDescription !== '商品描述'" class="detail-text">{{ product.detailDescription }}</text>
				<text v-else class="no-detail">暂无详情描述</text>
				
				<!-- 商品详情图片 -->
				<view v-if="goodsMessage" class="detail-images">
					<image 
						v-if="goodsMessage.goodsImgOne" 
						:src="goodsMessage.goodsImgOne" 
						mode="widthFix" 
						class="detail-image"
						@error="onImageError"
					></image>
					<image 
						v-if="goodsMessage.goodsImgTwo" 
						:src="goodsMessage.goodsImgTwo" 
						mode="widthFix" 
						class="detail-image"
						@error="onImageError"
					></image>
					<image 
						v-if="goodsMessage.goodsImgThree" 
						:src="goodsMessage.goodsImgThree" 
						mode="widthFix" 
						class="detail-image"
						@error="onImageError"
					></image>
				</view>
			</view>
		</view>

	

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
				<view class="left-actions">
				<view class="action-item">
					<u-icon name="home" size="20" color="#666"></u-icon>
					<text>店铺</text>
				</view>
				<view class="action-item">
						<image class="action-icon-img" src="/static/profile/官方客服.png" mode="aspectFit"></image>
					<text>客服</text>
				</view>
				<view class="action-item" @click="goToCart">
					<u-icon name="shopping-cart" size="20" color="#666"></u-icon>
					<text>购物车</text>
				</view>
			</view>
			<view class="right-actions">
				<view class="add-cart-btn" @click="addToCart">加入购物车</view>
				<view class="buy-now-btn" @click="buyNow">立即购买</view>
			</view>
		</view>

		<!-- 规格选择弹窗 -->
		<view class="spec-modal" v-if="showSpec" @click="hideSpecModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text>选择规格</text>
					<text class="iconfont icon-close" @click="hideSpecModal"></text>
				</view>
				<view class="spec-options">
					<view class="spec-group" v-for="specType in product.specTypes" :key="specType">
						<text class="group-title">{{ specType }}</text>
						<view class="option-list">
							<text class="option-item" 
								v-for="specValue in product.specValues[specType]" 
								:key="specValue"
								:class="{ 'selected': selectedSpec.specValues[specType] === specValue }"
								@click="selectSpecValue(specType, specValue)">
								{{ specValue }}
							</text>
						</view>
					</view>
					<view class="spec-group" v-if="product.specTypes.length === 0">
						<text class="group-title">规格</text>
						<view class="no-sku-tip">
							<text>该商品暂无规格选择</text>
						</view>
					</view>
					<view class="quantity-selector">
						<text class="quantity-label">数量</text>
						<view class="quantity-control">
							<text class="quantity-btn" @click="decreaseQuantity">-</text>
							<text class="quantity-value">{{ selectedSpec.quantity }}</text>
							<text class="quantity-btn" @click="increaseQuantity">+</text>
						</view>
						<text class="stock-info" v-if="getCurrentStock() > 0">库存: {{ getCurrentStock() }}</text>
						<text class="stock-info out-of-stock" v-else>库存不足</text>
					</view>
				</view>
				<view class="modal-footer">
					<button class="confirm-btn" @click="confirmSpec">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getUserId } from '../../utils/auth.js';
	import {get,post,del,put} from '../../utils/request.js'
export default {
	data() {
		return {
			product: {
				id: '',
				title: '',
				description: '',
				price: '0.00',
				memberPrice: '0.00',
				sold: 0,
				shipping: '0.00',
				isCollected: false,
				images: [],
				skuList: [], // 从后端获取的SKU列表
				specTypes: [], // 规格类型列表（如颜色、尺寸等）
				specValues: {}, // 规格值映射 {规格类型: [规格值列表]}
				detailDescription: '',
				businessId: null
			},
			goodsMessage: null, // 商品详情描述数据
			selectedSpec: {
				skuId: '', // 选中的SKU ID
				skuName: '', // 选中的SKU名称
				specValues: {}, // 选中的规格值 {规格类型: 规格值}
				quantity: 1
			},
			showSpec: false,
			deliveryAddress: '广东省广州市越秀区',
				reviews: [],
				defaultAvatar: '/static/logo.png',
				// 评价用户信息缓存
				userInfoMap: {},
				gatewayUrl: '',
			store: {
				id: '',
				name: '',
				logo: '/static/logo.png',
				rating: '0.0',
				followers: 0
			},
      recommendedProducts: [],
      reviewStats: { total: 0 },
			userId: Number(getUserId()),
		}
		
	},
	computed: {
    goodReviews() { return this.reviewStats.good || 0 },
    neutralReviews() { return this.reviewStats.neutral || 0 },
    badReviews() { return this.reviewStats.bad || 0 },
    imageReviews() { return this.reviewStats.withImage || 0 },
		// 安全的推荐商品数组
		safeRecommendedProducts() {
			try {
				return this.recommendedProducts || [];
			} catch (error) {
				console.error('获取推荐商品失败:', error);
				return [];
			}
		}
	},
	// 页面加载时获取商品详情
	onLoad(options) {
		console.log('商品详情页接收参数:', options);
		
		// 获取传递的商品ID
		const goodsId = options.id || options.goodsId;
		if (!goodsId) {
			console.error('未接收到商品ID参数');
			uni.showToast({
				title: '商品参数缺失',
				icon: 'none',
				duration: 2000
			});
			
			// 延迟返回上一页
			setTimeout(() => {
				uni.navigateBack();
			}, 2000);
			return;
		}
		
		console.log('开始加载商品ID:', goodsId, '的详情');
		// 读取网关地址用于补全图片URL
		import('../../config/env.js').then(m => { this.gatewayUrl = (m && m.default && m.default.GATEWAY_URL) || '' }).catch(() => {})
		
			// 加载商品详情
		this.loadGoodsDetail(goodsId);
			// 同时尝试加载部分评价用于预览
			this.loadAppraisePreview(goodsId)
	},
	methods: {
			// 跳转至评价页并切换到指定筛选
			goToReviewsWithTab(tab) {
				const pid = this.product && (this.product.id || this.product.goodsId)
				if (!pid) { uni.showToast({ title: '未获取到商品ID', icon: 'none' }); return }
				const safe = ['all','positive','neutral','negative','withImage']
				const t = safe.includes(tab) ? tab : 'all'
				uni.navigateTo({ url: `/pages/goodsReviews/goodsReviews?productId=${pid}&tab=${t}` })
			},
			// 点击某条预览评价，跳转到评价页并定位高亮
			goToReviewsReview(review) {
				const pid = this.product && (this.product.id || this.product.goodsId)
				if (!pid) {
					uni.showToast({ title: '未获取到商品ID', icon: 'none' })
					return
				}
				const rid = review && (review.id || review.appraiseId)
				const key = review && review.content ? encodeURIComponent(review.content.slice(0, 12)) : ''
				const extra = rid ? `&reviewId=${rid}` : (key ? `&reviewKey=${key}` : '')
				uni.navigateTo({
					url: `/pages/goodsReviews/goodsReviews?productId=${pid}${extra}`
				})
			},
		// 统一图片URL处理：相对路径补全为网关绝对URL
		resolveImageUrl(url) {
			if (!url) return ''
			const u = String(url).trim()
			if (/^https?:\/\//i.test(u)) return u
			const base = this.gatewayUrl || ''
			if (!base) return u
			if (u.startsWith('/')) return `${base}${u}`
			return `${base}/${u}`
		},
			// 拉取部分评价作为预览（与评价页保持一致字段）
			async loadAppraisePreview(goodsId) {
				try {
					const { get } = await import('../../utils/request.js')
					const res = await get('/appraise/list', { pageNum: 1, pageSize: 3, goodsId })
					const rows = (res && res.rows) || (res && res.data && res.data.rows) || []
				// 先批量拉取用户信息（排除匿名）
				const userIds = Array.from(new Set(rows.filter(r => !r.isAnonymous).map(r => r.userId).filter(Boolean)))
				if (userIds.length) {
					const results = await Promise.allSettled(userIds.map(id => get(`/user/${id}`)))
					results.forEach((rs, idx) => {
						if (rs.status === 'fulfilled') {
							const id = userIds[idx]
							const payload = rs.value
							const data = (payload && payload.data) || payload || {}
							this.$set(this.userInfoMap, id, {
								nickname: data.userNickname || '',
								account: data.userAccount || '',
								avatar: data.userImg || ''
							})
						}
					})
				}
                // 统计总数
                const total = Number((res && res.total) || (res && res.data && res.data.total) || rows.length || 0)
                const mapped = rows.map(item => {
					const info = item.userId ? this.userInfoMap[item.userId] : null
					return {
						username: item.isAnonymous ? '匿名评价' : ((info && (info.nickname || info.account)) || item.userNickname || item.userAccount || `用户***${String(item.userId || '').slice(-2)}`),
						avatar: this.resolveImageUrl((info && info.avatar) || ''),
							content: item.appraiseContent || '系统默认好评',
							spec: '',
							rating: Number(item.appraiseScore) || 0,
						images: (item.appraiseImg || '')
							.split(',')
							.map(s => this.resolveImageUrl(s.trim()))
							.filter(Boolean)
						}
                    })
                this.reviews = mapped
                this.reviewStats = {
                    total,
                    good: mapped.filter(r => (r.rating || 0) >= 4).length,
                    neutral: mapped.filter(r => (r.rating || 0) === 3).length,
                    bad: mapped.filter(r => (r.rating || 0) <= 2).length,
                    withImage: mapped.filter(r => Array.isArray(r.images) && r.images.length > 0).length
                }
				} catch (e) {
					// 静默失败，保持空列表
				}
			},
			// 预览评价图片
			previewImage(images, current) {
				if (!images || !images.length) return
				uni.previewImage({
					urls: images,
					current
				})
			},
		// 加载商品详情
		async loadGoodsDetail(goodsId) {
			try {
				uni.showLoading({
					title: '加载商品详情...'
				});
				
				// 调用商品详情API
				const { goodsApi } = await import('../../utils/goodsApi.js');
				const result = await goodsApi.getGoodsDetail(goodsId);
				
				console.log('商品详情API响应:', result);
				console.log('商品详情数据:', result.data);
				
				if (result && result.data) {
					const goodsData = result.data || {};
					
					// 更新商品数据 - 使用后端实体类的标准字段名
					this.product = {
						id: goodsData.goodsId || goodsId,
						title: goodsData.goodsName || '商品名称',
						description: goodsData.goodsDesc || '商品描述',
						price: goodsData.goodsPrice || '0.00',
						memberPrice: goodsData.goodsPrice || '0.00',
						originalPrice: goodsData.goodsDiscount || goodsData.goodsPrice || '0.00',
						images: goodsData.goodsImg ? [goodsData.goodsImg] : ['/static/logo.png'],
						sold: goodsData.sales || 0,
						stock: goodsData.goodsNumber || 0,
						shipping: goodsData.shipping || '0.00',
						isCollected: false,
						skuList: [], // SKU列表通过单独的API获取
						specTypes: [], // 规格类型通过解析SKU获取
						specValues: {}, // 规格值映射通过解析SKU获取
						detailDescription: goodsData.goodsDesc || '商品描述',
						businessId: goodsData.businessId
					};
					
					// 如果图片是字符串，转换为数组
					if (typeof this.product.images === 'string') {
						this.product.images = [this.product.images];
					}
					
					console.log('商品详情加载成功:', this.product);
					
					// 获取商家信息
					if (goodsData && goodsData.businessId) {
						this.loadBusinessInfo(goodsData.businessId);
					}
					
					// 获取商品详情描述
					this.loadGoodsMessage(goodsId);
					
					// 获取商品SKU列表
					this.loadGoodsSkuList(goodsId);
					
					// 获取店铺推荐商品
					if (goodsData && goodsData.businessId) {
						this.loadStoreGoods(goodsData.businessId, goodsId);
					}
					
					uni.hideLoading();
					uni.showToast({
						title: '商品详情加载成功',
						icon: 'success',
						duration: 1500
					});
				} else {
					console.warn('API返回数据为空，使用默认数据');
					this.product.id = goodsId;
					this.loadDefaultProduct();
				}
			} catch (error) {
				console.error('加载商品详情失败:', error);
				uni.hideLoading();
				
				uni.showToast({
					title: '加载商品详情失败',
					icon: 'none',
					duration: 2000
				});
				
				// 使用默认数据
				this.product.id = goodsId;
				this.loadDefaultProduct();
			}
		},
		
		// 加载默认商品数据
		loadDefaultProduct() {
			console.log('使用默认商品数据');
			// 设置默认的商品信息
			this.product = {
				...this.product,
				title: '测试商品 - 立即购买功能',
				description: '这是一个测试商品，用于验证立即购买功能',
				price: '99.99',
				memberPrice: '89.99',
				sold: 100,
				shipping: '10.00',
				images: ['/static/logo.png'],
				businessId: 1,
				skuList: [
					{
						id: 'test-sku-1',
						price: '99.99',
						goodsNumber: 50,
						spec: '默认规格',
						image: '/static/logo.png'
					}
				],
				specTypes: ['颜色', '尺寸'],
				specValues: {
					'颜色': ['红色', '蓝色', '绿色'],
					'尺寸': ['S', 'M', 'L', 'XL']
				}
			};
			
			// 设置默认选中的规格
			this.selectedSpec = {
				skuId: 'test-sku-1',
				skuName: '测试SKU',
				specValues: {
					'颜色': '红色',
					'尺寸': 'M'
				},
				quantity: 1
			};
			
			console.log('默认商品数据设置完成:', this.product);
		},
		
		// 加载商品详情描述
		async loadGoodsMessage(goodsId) {
			try {
				console.log('开始加载商品ID:', goodsId, '的详情描述');
				
				// 调用商品详情描述API
				const { goodsApi } = await import('../../utils/goodsApi.js');
				const result = await goodsApi.getGoodsMessage(goodsId);
				
				console.log('商品详情描述API响应:', result);
				
				if (result && result.data) {
					const messageData = result.data;
					
					// 保存商品详情描述数据
					this.goodsMessage = messageData;
					
					// 更新商品详情描述
					this.product.detailDescription = messageData.goodsContent || this.product.detailDescription;
					
					console.log('商品详情描述加载成功:', messageData);
				} else {
					console.log('商品详情描述为空，使用默认描述');
				}
			} catch (error) {
				console.error('加载商品详情描述失败:', error);
				// 不显示错误提示，因为详情描述不是必需的
			}
		},
		
		// 加载商品SKU列表
		async loadGoodsSkuList(goodsId) {
			try {
				console.log('开始加载商品ID:', goodsId, '的SKU列表');
				
				// 调用SKU列表API
				const { goodsApi } = await import('../../utils/goodsApi.js');
				const result = await goodsApi.getGoodsSkuList(goodsId);
				
				console.log('SKU列表API响应:', result);
				
				if (result && (result.data || result.rows)) {
					// 支持不同的数据结构：data 或 rows
					const skuData = result.data || result.rows || [];
					
					// 处理SKU数据，解析规格信息
					const processedSkuList = skuData.map(sku => ({
						id: sku.skuId,
						price: sku.price,
						goodsNumber: sku.goodsNumber,
						spec: sku.spec,
						image: sku.image,
						skuCode: sku.skuCode
					})).filter(sku => sku.id); // 过滤掉无效的SKU
					
					// 保存SKU列表数据
					this.product.skuList = processedSkuList;
					
					// 解析规格类型和规格值
					this.parseSpecData(processedSkuList);
					
					// 如果SKU列表不为空，尝试选择第一个SKU
					if (processedSkuList.length > 0) {
						this.selectFirstSku(processedSkuList[0]);
					}
					
					console.log('SKU列表加载成功:', processedSkuList);
				} else {
					console.log('SKU列表为空，使用默认SKU');
					this.product.skuList = []; // 确保SKU列表为空，避免错误
					this.product.specTypes = [];
					this.product.specValues = {};
				}
			} catch (error) {
				console.error('加载SKU列表失败:', error);
				this.product.skuList = []; // 确保SKU列表为空，避免错误
				this.product.specTypes = [];
				this.product.specValues = {};
			}
		},
		
		// 解析规格数据
		parseSpecData(skuList) {
			try {
				const specTypes = new Set(); // 规格类型集合
				const specValuesMap = {}; // 规格值映射
				
				skuList.forEach(sku => {
					try {
						// 解析规格JSON
						const specArray = JSON.parse(sku.spec || '[]');
						if (Array.isArray(specArray)) {
							specArray.forEach(specItem => {
								if (specItem && specItem.name && specItem.value) {
									const specName = specItem.name.trim();
									const specValue = specItem.value.trim();
									
									// 添加规格类型
									specTypes.add(specName);
									
									// 添加规格值
									if (!specValuesMap[specName]) {
										specValuesMap[specName] = new Set();
									}
									specValuesMap[specName].add(specValue);
								}
							});
						}
					} catch (parseError) {
						console.warn('解析SKU规格JSON失败:', sku.spec, parseError);
					}
				});
				
				// 转换为数组格式
				this.product.specTypes = Array.from(specTypes);
				this.product.specValues = {};
				Object.keys(specValuesMap).forEach(specName => {
					this.product.specValues[specName] = Array.from(specValuesMap[specName]);
				});
				
				console.log('规格数据解析完成:', {
					specTypes: this.product.specTypes,
					specValues: this.product.specValues
				});
			} catch (error) {
				console.error('解析规格数据失败:', error);
				this.product.specTypes = [];
				this.product.specValues = {};
			}
		},
		
		// 选择第一个SKU
		selectFirstSku(sku) {
			try {
				this.selectedSpec.skuId = sku.id;
				this.selectedSpec.skuName = sku.skuName;
				
				// 解析第一个SKU的规格值
				const specArray = JSON.parse(sku.spec || '[]');
				this.selectedSpec.specValues = {};
				if (Array.isArray(specArray)) {
					specArray.forEach(specItem => {
						if (specItem && specItem.name && specItem.value) {
							this.selectedSpec.specValues[specItem.name.trim()] = specItem.value.trim();
						}
					});
				}
				
				console.log('选择第一个SKU:', this.selectedSpec);
			} catch (error) {
				console.error('选择第一个SKU失败:', error);
			}
		},
		
		// 图片加载错误处理
		onImageError(e) {
			console.log('图片加载失败:', e);
			// 设置默认图片
			e.target.src = '/static/logo.png';
		},
		
		// 处理推荐商品点击
		handleProductClick(item) {
			if (item && item.id) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${item.id}`
				});
			}
		},
		
		// 加载店铺推荐商品
		async loadStoreGoods(businessId, currentGoodsId) {
			try {
				console.log('开始加载店铺ID:', businessId, '的推荐商品');
				
				// 调用店铺商品API
				const { goodsApi } = await import('../../utils/goodsApi.js');
				const result = await goodsApi.getStoreGoods(businessId);
				
				console.log('店铺商品API响应:', result);
				
				if (result && result.rows && Array.isArray(result.rows)) {
					// 过滤掉当前商品，避免重复显示
					const filteredGoods = result.rows.filter(goods => {
						const goodsId = goods.goodsId || goods.id;
						return goodsId != currentGoodsId;
					});
					
					// 处理商品数据
					this.recommendedProducts = filteredGoods.map(goods => ({
						id: goods.goodsId || goods.id,
						title: goods.goodsName || goods.title || goods.name || '商品名称',
						image: goods.goodsImg || goods.img || goods.image || '/static/logo.png',
						price: goods.goodsPrice || goods.price || '0.00'
					}));
					
					console.log('店铺推荐商品加载成功，数量:', this.recommendedProducts.length);
				} else {
					console.log('店铺商品数据为空');
					this.recommendedProducts = [];
				}
			} catch (error) {
				console.error('加载店铺推荐商品失败:', error);
				this.recommendedProducts = [];
			}
		},
		
		// 加载商家信息
		async loadBusinessInfo(businessId) {
			try {
				console.log('开始加载商家ID:', businessId, '的信息');
				
				// 调用商家信息API
				const { businessApi } = await import('../../utils/goodsApi.js');
				const result = await businessApi.getBusinessInfo(businessId);
				
				console.log('商家信息API响应:', result);
				
				if (result && result.data) {
					const businessData = result.data || {};
					
					// 更新商家数据 - 添加安全的空值检查
					this.store = {
						id: (businessData && businessData.businessId) || (businessData && businessData.id) || businessId || '',
						name: (businessData && businessData.businessName) || (businessData && businessData.name) || '商家名称',
						logo: (businessData && businessData.businessLogo) || (businessData && businessData.logo) || '/static/logo.png',
						rating: (businessData && businessData.businessRating) || (businessData && businessData.rating) || '0.0',
						followers: (businessData && businessData.businessFollowers) || (businessData && businessData.followers) || 0
					};
					
					console.log('商家信息加载成功:', this.store);
				} else {
					console.warn('商家API返回数据为空，使用默认数据');
					this.loadDefaultBusinessInfo();
				}
			} catch (error) {
				console.error('加载商家信息失败:', error);
				// 使用默认数据
				this.loadDefaultBusinessInfo();
			}
		},
		
		// 加载默认商家数据
		loadDefaultBusinessInfo() {
			console.log('使用默认商家数据');
			this.store = {
				...this.store,
				name: '商家信息加载中...',
				rating: '0.0',
				followers: 0
			};
		},
		
		toggleCollect() {
			this.product.isCollected = !this.product.isCollected;
			uni.showToast({
				title: this.product.isCollected ? '已收藏' : '已取消收藏',
				icon: 'success'
			});
		},
		showSpecModal() {
			this.showSpec = true;
		},
		hideSpecModal() {
			this.showSpec = false;
		},
		selectSku(sku) {
			this.selectedSpec.skuId = sku.id;
			this.selectedSpec.skuName = sku.skuName;
		},
		decreaseQuantity() {
			if (this.selectedSpec.quantity > 1) {
				this.selectedSpec.quantity--;
			}
		},
		increaseQuantity() {
			// 获取当前选中SKU的库存
			const currentSku = this.product.skuList.find(sku => sku.id === this.selectedSpec.skuId);
			const maxStock = currentSku ? currentSku.goodsNumber : 999;
			
			if (this.selectedSpec.quantity < maxStock) {
				this.selectedSpec.quantity++;
			} else {
				uni.showToast({
					title: '已达到最大库存数量',
					icon: 'none'
				});
			}
		},
		confirmSpec() {
			// 检查是否选择了所有规格
			const allSpecsSelected = this.product.specTypes.every(specType => 
				this.selectedSpec.specValues[specType]
			);
			
			if (!allSpecsSelected) {
				uni.showToast({
					title: '请选择所有规格',
					icon: 'none'
				});
				return;
			}
			
			// 检查是否找到了对应的SKU
			if (!this.selectedSpec.skuId) {
				uni.showToast({
					title: '所选规格组合无货',
					icon: 'none'
				});
				return;
			}
			
			this.hideSpecModal();
			uni.showToast({
				title: '规格已选择',
				icon: 'success'
			});
		},
		addToCart() {
			// 检查是否选择了所有规格
			if (this.product.specTypes.length > 0) {
				const allSpecsSelected = this.product.specTypes.every(specType => 
					this.selectedSpec.specValues[specType]
				);
				
				if (!allSpecsSelected) {
					uni.showToast({
						title: '请先选择规格',
						icon: 'none'
					});
					this.showSpecModal();
					return;
				}
				
				if (!this.selectedSpec.skuId) {
					uni.showToast({
						title: '所选规格组合无货',
						icon: 'none'
					});
					this.showSpecModal();
					return;
				}
			}
			
			uni.showToast({
				title: '已加入购物车',
				icon: 'success'
			});
		},
		

		buyNow() {
			// 检查是否选择了所有规格
			if (this.product.specTypes.length > 0) {
				const allSpecsSelected = this.product.specTypes.every(specType => 
					this.selectedSpec.specValues[specType]
				);
				
				if (!allSpecsSelected) {
					uni.showToast({
						title: '请先选择规格',
						icon: 'none'
					});
					this.showSpecModal();
					return;
				}
				
				if (!this.selectedSpec.skuId) {
					uni.showToast({
						title: '所选规格组合无货',
						icon: 'none'
					});
					this.showSpecModal();
					return;
				}
			}
			
			// 检查库存
			const currentSku = this.product.skuList.find(sku => sku.id === this.selectedSpec.skuId);
			if (currentSku && this.selectedSpec.quantity > currentSku.goodsNumber) {
				uni.showToast({
					title: `库存不足，当前库存: ${currentSku.goodsNumber}`,
					icon: 'none'
				});
				return;
			}
			
			// 跳转到订单提交页面，传递商品信息
			this.navigateToSubmitOrder();
		},
		
		// 跳转到订单提交页面
		navigateToSubmitOrder() {
			try {
				// 构建传递给订单提交页面的参数
				const orderParams = {
					productId: this.product.id,
					productName: this.product.title,
					productImage: this.product.images && this.product.images.length > 0 ? this.product.images[0] : '/static/logo.png',
					productPrice: this.product.price,
					productSpecs: this.getSelectedSpecText() || '默认规格',
					productQuantity: this.selectedSpec.quantity,
					productSkuId: this.selectedSpec.skuId,
					businessId: this.product.businessId || 1,
					shipping: this.product.shipping || '0.00'
				};
				
				console.log('准备跳转到订单提交页面，参数:', orderParams);
				
				// 将参数编码并跳转
				const queryString = Object.keys(orderParams)
					.map(key => `${key}=${encodeURIComponent(orderParams[key])}`)
					.join('&');
				
				uni.navigateTo({
					url: `/pages/submitorder/submitorder?${queryString}`,
					success: () => {
						console.log('跳转到订单提交页面成功');
					},
					fail: (err) => {
						console.error('跳转到订单提交页面失败:', err);
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						});
					}
				});
				
			} catch (error) {
				console.error('跳转到订单提交页面失败:', error);
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none'
				});
			}
		},
		
		// 创建订单并跳转
		async createOrderAndNavigate() {
			try {
				uni.showLoading({
					title: '创建订单中...'
				});
				
				// 构建订单数据
				const orderData = {
					userId: uni.getStorageSync('userId') || 1, // 从本地存储获取用户ID
					goodsId: this.product.id,
					businessId: this.product.businessId || 1, // 商家ID
					goodsSpecs: this.getSelectedSpecText() || '默认规格',
					orderPrice: parseFloat(this.product.price),
					orderCreateTime: new Date(),
					orderStatus: 0, // 0-待支付
					orderComment: '',
					orderNumber: this.generateOrderNumber(),
					orderPostPrice: parseFloat(this.product.shipping || 0),
					orderType: 0, // 0-未删除
					addressId: 1, // 默认地址ID
					// 商品相关信息
					goodsname: this.product.title,
					goodsprice: this.product.price,
					goodsnumber: this.selectedSpec.quantity.toString(),
					goodsimg: this.product.images && this.product.images.length > 0 ? this.product.images[0] : '/static/logo.png',
					goodsVirtual: 0 // 0-实物商品
				};
				
				console.log('准备创建的订单数据:', orderData);
				
				// 调用后端API创建订单
				const response = await this.createOrder(orderData);
				
				if (response && response.code === 200) {
					uni.hideLoading();
					uni.showToast({
						title: '订单创建成功',
						icon: 'success'
					});
					
					// 订单创建成功后，可以在这里添加其他逻辑
					// 比如显示订单信息、跳转到支付页面等
					console.log('订单创建成功，订单号:', orderData.orderNumber);
					
				} else {
					throw new Error(response?.msg || '创建订单失败');
				}
				
			} catch (error) {
				uni.hideLoading();
				console.error('创建订单失败:', error);
				uni.showToast({
					title: error.message || '创建订单失败，请重试',
					icon: 'none'
				});
			}
		},
		
		// 调用后端API创建订单
		async createOrder(orderData) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: 'http://localhost:8080/zmhshop/orderst',
					method: 'POST',
					data: orderData,
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						console.log('创建订单API响应:', res);
						resolve(res.data);
					},
					fail: (err) => {
						console.error('创建订单API请求失败:', err);
						reject(err);
					}
				});
			});
		},
		
		// 生成订单号
		generateOrderNumber() {
			const timestamp = Date.now();
			const random = Math.floor(Math.random() * 1000);
			return `ORDER${timestamp}${random}`;
		},
		

		goToCart() {
			uni.switchTab({
				url: '/pages/cart/cart'
			});
		},
		// 安全的商品点击处理
		handleProductClick(item) {
			console.log('推荐商品点击事件触发，商品数据:', item);
			try {
				if (item && item.id) {
					console.log('准备跳转到商品详情，商品ID:', item.id);
					this.goToProduct(item.id);
				} else {
					console.warn('商品数据无效:', item);
					uni.showToast({
						title: '商品数据无效',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('商品点击处理失败:', error);
				uni.showToast({
					title: '操作失败',
					icon: 'none'
				});
			}
		},
		
		// 安全的图片获取
		getSafeImage(item) {
			try {
				return (item && item.image) || '/static/logo.png';
			} catch (error) {
				console.error('获取图片失败:', error);
				return '/static/logo.png';
			}
		},
		
		// 安全的标题获取
		getSafeTitle(item) {
			try {
				return (item && item.title) || '商品名称';
			} catch (error) {
				console.error('获取标题失败:', error);
				return '商品名称';
			}
		},
		
		// 安全的价格获取
		getSafePrice(item) {
			try {
				return (item && item.price) || '0.00';
			} catch (error) {
				console.error('获取价格失败:', error);
				return '0.00';
			}
		},
		
		goToProduct(productId) {
			if (productId) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${productId}`
				});
			} else {
				uni.showToast({
					title: '商品ID无效',
					icon: 'none'
				});
			}
		},
		goToReviews() {
			// 跳转到商品评价页，并携带商品ID用于后端查询
			const pid = this.product && (this.product.id || this.product.goodsId)
			if (pid) {
				uni.navigateTo({
					url: `/pages/goodsReviews/goodsReviews?productId=${pid}`
				});
			} else {
				uni.showToast({ title: '未获取到商品ID', icon: 'none' })
			}
		},
		selectSpecValue(specType, specValue) {
			// 更新选中的规格值
			this.selectedSpec.specValues[specType] = specValue;
			
			// 根据选中的规格值查找对应的SKU
			this.findSkuBySpecValues();
		},
		
		// 根据规格值查找对应的SKU
		findSkuBySpecValues() {
			try {
				// 检查是否所有规格都已选择
				const allSpecsSelected = this.product.specTypes.every(specType => 
					this.selectedSpec.specValues[specType]
				);
				
				if (!allSpecsSelected) {
					// 如果还有规格未选择，只更新显示文本
					this.selectedSpec.skuName = Object.values(this.selectedSpec.specValues).join(' ');
					return;
				}
				
				// 查找匹配的SKU
				const matchedSku = this.product.skuList.find(sku => {
					try {
						const specArray = JSON.parse(sku.spec || '[]');
						if (!Array.isArray(specArray)) return false;
						
						// 检查所有规格值是否匹配
						return this.product.specTypes.every(specType => {
							const selectedValue = this.selectedSpec.specValues[specType];
							return specArray.some(specItem => 
								specItem.name === specType && specItem.value === selectedValue
							);
						});
					} catch (error) {
						console.warn('解析SKU规格失败:', sku.spec, error);
						return false;
					}
				});
				
				if (matchedSku) {
					// 找到匹配的SKU，更新选中信息
					this.selectedSpec.skuId = matchedSku.id;
					this.selectedSpec.skuName = matchedSku.skuName || Object.values(this.selectedSpec.specValues).join(' ');
					
					// 更新商品价格显示（可选）
					if (matchedSku.price && matchedSku.price !== this.product.price) {
						this.product.price = matchedSku.price;
					}
					
					// 检查库存，如果当前选择的数量超过库存，调整为库存数量
					if (this.selectedSpec.quantity > matchedSku.goodsNumber) {
						this.selectedSpec.quantity = matchedSku.goodsNumber;
						if (matchedSku.goodsNumber > 0) {
							uni.showToast({
								title: `库存不足，已调整为最大可购买数量: ${matchedSku.goodsNumber}`,
								icon: 'none'
							});
						}
					}
					
					console.log('找到匹配的SKU:', matchedSku);
				} else {
					// 未找到匹配的SKU
					console.warn('未找到匹配的SKU，规格值:', this.selectedSpec.specValues);
					this.selectedSpec.skuId = '';
					this.selectedSpec.skuName = Object.values(this.selectedSpec.specValues).join(' ');
				}
			} catch (error) {
				console.error('查找SKU失败:', error);
			}
		},
		getSelectedSpecText() {
			const selectedSpecs = [];
			
			// 遍历所有规格类型，显示已选择的规格值
			this.product.specTypes.forEach(specType => {
				const selectedValue = this.selectedSpec.specValues[specType];
				if (selectedValue) {
					selectedSpecs.push(`${specType}: ${selectedValue}`);
				}
			});
			
			if (selectedSpecs.length === 0) {
				return '请选择规格';
			}
			
			return selectedSpecs.join(' ');
		},
		getCurrentStock() {
			if (this.selectedSpec.skuId) {
				const currentSku = this.product.skuList.find(sku => sku.id === this.selectedSpec.skuId);
				return currentSku ? currentSku.goodsNumber : 0;
			}
			return 0;
		}
	}
}
</script>

<style scoped>
.product-detail {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}



/* 商品图片 */
.product-images {
	background-color: #fff;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
	overflow: hidden;
}

.swiper {
	height: 600rpx;
}

.product-image {
	width: 100%;
	height: 100%;
}

.video-play {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 80rpx;
	height: 80rpx;
	background-color: rgba(0, 0, 0, 0.6);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
}

/* 价格区域 */
.price-section {
	background-color: #fff;
	padding: 30rpx;
	margin-top: 20rpx;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
}

.price-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.price {
	font-size: 48rpx;
	color: #ff4444;
	font-weight: bold;
}

.sold {
	font-size: 28rpx;
	color: #999;
}

.member-price {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.coupon-section {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.coupon-tag {
	background-color: #ff4444;
	color: #fff;
	padding: 10rpx 20rpx;
	border-radius: 10rpx;
	font-size: 24rpx;
}

.get-coupon {
	background-color: #ff4444;
	color: #fff;
	border: none;
	padding: 10rpx 20rpx;
	border-radius: 10rpx;
	font-size: 24rpx;
	display: flex;
	align-items: center;
	gap: 5rpx;
}

/* 商品信息 */
.product-info {
	background-color: #fff;
	padding: 30rpx;
	margin-top: 20rpx;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
}

.product-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
	line-height: 1.4;
	color: #333;
}

.product-desc {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 30rpx;
	line-height: 1.5;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
}

.share-btn, .collect-btn {
	display: flex;
	align-items: center;
	gap: 10rpx;
	padding: 20rpx 40rpx;
	border: 1px solid #ddd;
	border-radius: 10rpx;
	background-color: #fff;
	font-size: 28rpx;
	color: #666;
}

.collected {
	background-color: #ff4444;
	color: #fff;
	border-color: #ff4444;
}

/* 规格选择 */
.specification-section {
	background-color: #fff;
	margin-top: 20rpx;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
}

.spec-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	border-bottom: 1px solid #f0f0f0;
}

.spec-label {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.selected-info {
	font-size: 24rpx;
	color: #666;
}

.spec-desc {
	font-size: 24rpx;
	color: #666;
}

.delivery-address {
	padding: 30rpx;
	font-size: 28rpx;
	color: #666;
}

/* 评价区域 */
.reviews-section {
	background-color: #f8f8f8;
	margin-top: 20rpx;
	padding: 30rpx;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
	cursor: pointer;
	transition: all 0.3s ease;
}

.reviews-section:active {
	background-color: #f0f0f0;
	transform: scale(0.98);
}

.reviews-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 30rpx;
}

.reviews-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.reviews-more {
	display: flex;
	align-items: center;
	gap: 10rpx;
	font-size: 28rpx;
	color: #999;
}

.reviews-filters {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    gap: 10rpx;
    margin-bottom: 24rpx;
}

.filter-item {
    flex: 1 1 0;
    text-align: center;
    padding: 8rpx 12rpx;
	border: 1px solid #ddd;
    border-radius: 16rpx;
	font-size: 24rpx;
	color: #666;
	background-color: #fff;
}

.filter-item.active {
	background-color: #ff4444;
	color: #fff;
	border-color: #ff4444;
}

.review-item {
	margin-bottom: 30rpx;
}

.review-user {
	display: flex;
	align-items: center;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.user-avatar {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
}

.username {
	font-size: 28rpx;
	color: #333;
}

.rating {
    color: #ff4444;
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 6rpx;
}

.review-content {
	font-size: 28rpx;
	color: #333;
	line-height: 1.5;
}

.review-spec {
	font-size: 24rpx;
	color: #999;
	margin-top: 10rpx;
}

.review-images {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    margin-top: 10rpx;
}

.review-image-item {
    width: 32%;
    height: 0;
    padding-bottom: 32%;
    position: relative;
    overflow: hidden;
    border-radius: 8rpx;
}

.review-image-item image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

/* 店铺信息 */
.store-section {
	background-color: #f8f8f8;
	margin-top: 20rpx;
	padding: 30rpx;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.store-info {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.store-logo {
	width: 80rpx;
	height: 80rpx;
	border-radius: 10rpx;
}

.store-name {
	display: flex;
	align-items: center;
	gap: 10rpx;
	margin-bottom: 10rpx;
}

.self-operated {
	background-color: #ff4444;
	color: #fff;
	padding: 4rpx 10rpx;
	border-radius: 6rpx;
	font-size: 20rpx;
}

.store-rating {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.rating-score {
	font-size: 28rpx;
	color: #ff4444;
	font-weight: bold;
}

.rating-stars {
    color: #ff4444;
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 6rpx;
}

.followers {
	font-size: 24rpx;
	color: #666;
}

.visit-store {
	background-color: #ff4444;
	color: #fff;
	border: none;
	padding: 20rpx 40rpx;
	border-radius: 10rpx;
	font-size: 28rpx;
}

/* 推荐商品 */
.recommended-section {
	background-color: #f8f8f8;
	margin-top: 20rpx;
	padding: 30rpx;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 30rpx;
}

.recommended-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20rpx;
}

.recommended-item {
	display: flex;
	flex-direction: column;
}

.item-image {
	width: 100%;
	height: 200rpx;
	border-radius: 10rpx;
	margin-bottom: 10rpx;
}

.item-title {
	font-size: 24rpx;
	color: #333;
	line-height: 1.3;
	margin-bottom: 10rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.item-price {
	font-size: 28rpx;
	color: #ff4444;
	font-weight: bold;
}

/* 商品详情 */
.product-details {
	background-color: #fff;
	margin-top: 20rpx;
	padding: 30rpx;
	border-radius: 15rpx;
	margin: 20rpx 30rpx;
}

.detail-content {
	font-size: 28rpx;
	color: #333;
	line-height: 1.6;
}

.detail-text {
	margin-bottom: 30rpx;
	line-height: 1.8;
}

.detail-images {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.detail-image {
	width: 100%;
	border-radius: 10rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.no-detail {
	color: #999;
	font-style: italic;
	text-align: center;
	display: block;
	padding: 40rpx 0;
}


/* 底部操作栏 */
.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 16rpx 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-top: 1px solid #f0f0f0;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.left-actions {
    display: flex;
	gap: 28rpx;
    flex: 0 0 auto;
}

.action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 6rpx;
    font-size: 22rpx;
    color: #666;
    white-space: nowrap;
    line-height: 1;
}

.action-icon-img {
    width: 40rpx;
    height: 40rpx;
    display: block;
}

.right-actions {
	display: grid;
	grid-auto-flow: column;
	grid-auto-columns: minmax(0, 1fr);
	gap: 16rpx;
	margin-left: auto;
	justify-content: end;
	align-items: center;
	max-width: 60%;
}

.add-cart-btn, .buy-now-btn {
	padding: 20rpx 28rpx;
	border: none;
	border-radius: 10rpx;
	font-size: 26rpx;
	font-weight: bold;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
	min-width: 160rpx;
    flex-shrink: 0;
  overflow: hidden;
  text-overflow: ellipsis;
}

.add-cart-btn {
	background-color: #ffa726;
	color: #fff;
}

.buy-now-btn {
	background-color: #ff4444;
	color: #fff;
}

/* 规格选择弹窗 */
.spec-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: flex-end;
}

.modal-content {
	background-color: #fff;
	width: 100%;
	border-radius: 20rpx 20rpx 0 0;
	padding: 30rpx;
	max-height: 70vh;
	overflow-y: auto;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 30rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.spec-group {
	margin-bottom: 30rpx;
}

.group-title {
	font-size: 28rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.option-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.option-item {
	padding: 20rpx 30rpx;
	border: 1px solid #ddd;
	border-radius: 10rpx;
	font-size: 28rpx;
	color: #333;
}

.option-item.selected {
	background-color: #ff4444;
	color: #fff;
	border-color: #ff4444;
}

.quantity-selector {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 30rpx;
}

.quantity-label {
	font-size: 28rpx;
	font-weight: bold;
}

.quantity-control {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.quantity-btn {
	width: 60rpx;
	height: 60rpx;
	border: 1px solid #ddd;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	color: #333;
}

.quantity-value {
	font-size: 32rpx;
	font-weight: bold;
	min-width: 80rpx;
	text-align: center;
}

.stock-info {
	font-size: 24rpx;
	color: #ff4444;
	font-weight: bold;
	margin-top: 10rpx;
}

.stock-info.out-of-stock {
	color: #999;
}

.confirm-btn {
	background-color: #ff4444;
	color: #fff;
	border: none;
	padding: 20rpx;
	border-radius: 10rpx;
	font-size: 32rpx;
	width: 100%;
}

.no-sku-tip {
	padding: 20rpx 30rpx;
	background-color: #f0f0f0;
	border-radius: 10rpx;
	font-size: 28rpx;
	color: #666;
	text-align: center;
}

</style> 